import React, { useState, useEffect } from 'react';
import { Card, CardContent } from '../components/UI/Card';
import { Badge } from '../components/UI/Badge';
import { mockApi } from '../services/mockApi';
import { api } from '../services/api';
import { 
  TrendingUp,
  TrendingDown,
  Package,
  Box,
  Users,
  Clock,
  Target,
  Activity,
  BarChart3,
  Calendar,
  Hash,
  ShoppingCart,
  ChevronDown,
  Zap,
  Award,
  Star,
  Sparkles,
  PieChart as PieChartIcon
} from 'lucide-react';
import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  BarChart,
  Bar,
  PieChart,
  Pie,
  Cell,
  Legend
} from 'recharts';

// 月份选项 - 添加2024年的月份
const monthOptions = [
  { value: '2024-01', label: '2024年1月' },
  { value: '2024-02', label: '2024年2月' },
  { value: '2024-03', label: '2024年3月' },
  { value: '2024-04', label: '2024年4月' },
  { value: '2024-05', label: '2024年5月' },
  { value: '2024-06', label: '2024年6月' },
  { value: '2024-07', label: '2024年7月' },
  { value: '2024-08', label: '2024年8月' },
  { value: '2024-09', label: '2024年9月' },
  { value: '2024-10', label: '2024年10月' },
  { value: '2024-11', label: '2024年11月' },
  { value: '2024-12', label: '2024年12月' },
  { value: '2025-01', label: '2025年1月' },
  { value: '2025-02', label: '2025年2月' },
  { value: '2025-03', label: '2025年3月' },
  { value: '2025-04', label: '2025年4月' },
  { value: '2025-05', label: '2025年5月' },
  { value: '2025-06', label: '2025年6月' },
  { value: '2025-07', label: '2025年7月' },
];

// 自定义饼图Tooltip组件 - 更华丽的设计
const CustomPieTooltip = ({ active, payload, label }: any) => {
  if (active && payload && payload.length) {
    return (
      <div className="bg-white/95 backdrop-blur-lg border border-gray-200/50 rounded-2xl p-4 shadow-2xl transform transition-all duration-300 hover:scale-105">
        <div className="flex items-center space-x-3">
          <div 
            className="w-4 h-4 rounded-full shadow-lg animate-pulse" 
            style={{ backgroundColor: payload[0].payload.color }}
          />
          <span className="font-semibold text-gray-800 text-lg">{payload[0].payload.name}</span>
        </div>
        <div className="mt-2 flex items-baseline space-x-2">
          <span className="text-2xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
            {payload[0].value}%
          </span>
          <span className="text-sm text-gray-600">占比</span>
        </div>
        <div className="mt-2 h-1 bg-gradient-to-r from-blue-400 to-purple-400 rounded-full animate-pulse" />
      </div>
    );
  }
  return null;
};

// 通用深色主题Tooltip - 更华丽的设计
const DarkTooltip = ({ active, payload, label, formatter }: any) => {
  if (active && payload && payload.length) {
    return (
      <div className="bg-white/95 backdrop-blur-lg border border-gray-200/50 rounded-2xl p-4 shadow-2xl transform transition-all duration-300 hover:scale-105">
        {label && (
          <div className="flex items-center space-x-2 mb-3">
            <Sparkles className="w-4 h-4 text-yellow-500" />
            <p className="font-semibold text-gray-800 text-lg">{label}</p>
          </div>
        )}
        <div className="space-y-2">
          {payload.map((entry: any, index: number) => (
            <div key={index} className="flex items-center justify-between space-x-6 p-2 rounded-lg bg-gray-50/50">
              <div className="flex items-center space-x-3">
                <div 
                  className="w-3 h-3 rounded-full shadow-sm animate-pulse" 
                  style={{ backgroundColor: entry.color }}
                />
                <span className="text-gray-700 font-medium">{entry.name || entry.dataKey}</span>
              </div>
              <span className="font-bold text-gray-900 text-lg">
                {formatter ? formatter(entry.value, entry.name) : entry.value}
              </span>
            </div>
          ))}
        </div>
        <div className="mt-3 h-1 bg-gradient-to-r from-blue-400 via-purple-400 to-pink-400 rounded-full animate-pulse" />
      </div>
    );
  }
  return null;
};

export const Analytics: React.FC = () => {
  const [currentTime, setCurrentTime] = useState(new Date());
  const [selectedMonth, setSelectedMonth] = useState('2024-01');
  const [dailyOrderData, setDailyOrderData] = useState<Array<{
    day: string;
    orders: number;
    outbound: number;
  }>>([]);
  const [orderTypeData, setOrderTypeData] = useState<Array<{
    name: string;
    value: number;
    color: string;
  }>>([]);
  const [dashboardStats, setDashboardStats] = useState({
    monthlyOrders: 0,       // 本月订单数
    monthlyOutbound: 0,     // 本月总出库量
    totalCustomers: 0,      // 客户总数
    productCategories: 0    // 货物品类数
  });
  const [popularProductData, setPopularProductData] = useState<Array<{
    name: string;
    outbound: number;
    unit: string;
    orders: number;
  }>>([]);
  const [loading, setLoading] = useState(false);
  const [animationKey, setAnimationKey] = useState(0);
  const [visibleLines, setVisibleLines] = useState({
    orders: true,
    outbound: true
  });
  const [visiblePieSegments, setVisiblePieSegments] = useState<Record<string, boolean>>({});

  // 时间更新
  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000);
    return () => clearInterval(timer);
  }, []);

  // 获取大屏数据
  const fetchAnalyticsData = async (month: string) => {
    try {
      setLoading(true);
      const data = await api.analytics.getOrderData(month);
      
      // 更新KPI指标
      setDashboardStats({
        monthlyOrders: data.largeScreenVO.orderCount,
        monthlyOutbound: data.largeScreenVO.totalRolls,
        totalCustomers: data.largeScreenVO.customerCount,
        productCategories: data.cargoCount,
      });

      // 更新日度趋势数据
      const dailyData = data.largeScreenLineVOs.map(item => ({
        day: item.orderDay,
        orders: item.totalOrders,
        outbound: item.totalOutbound,
      }));
      setDailyOrderData(dailyData);

      // 更新订单类型分布 - 直接使用中文值
      const pieData = data.largeScreenPieVOs.map(item => ({
        name: item.orderType, // 直接使用后端返回的中文值
        value: Math.round((item.orderCount / data.largeScreenVO.orderCount) * 100),
        color: item.orderType === '镇内订单' ? '#00d4ff' : '#00ff88', // 根据中文值设置颜色
      }));
      setOrderTypeData(pieData);

      // 更新热门货物数据
      const cargoData = data.largeScreenCargoVO.map(item => ({
        name: item.productName,
        outbound: item.totalOutbound,
        unit: item.unit,
        orders: item.orderCount,
      }));
      setPopularProductData(cargoData);

      // 触发动画重新渲染
      setAnimationKey(prev => prev + 1);

    } catch (error) {
      console.error('获取大屏数据失败:', error);
      // 获取数据失败时，保持空状态，不显示默认值
      setDashboardStats({
        monthlyOrders: 0,
        monthlyOutbound: 0,
        totalCustomers: 0,
        productCategories: 0,
      });
      setDailyOrderData([]);
      setOrderTypeData([]);
      setPopularProductData([]);
    } finally {
      setLoading(false);
    }
  };

  // 初始化和月份切换时获取数据
  useEffect(() => {
    fetchAnalyticsData(selectedMonth);
  }, [selectedMonth]);

  // 在useEffect中初始化饼图可见性
  useEffect(() => {
    if (orderTypeData.length > 0) {
      const initialVisibility = orderTypeData.reduce((acc, item) => {
        acc[item.name] = true;
        return acc;
      }, {} as Record<string, boolean>);
      setVisiblePieSegments(initialVisibility);
    }
  }, [orderTypeData]);

  // 将CustomAreaLegend移到这里
  const CustomAreaLegend = () => {
    const legendItems = [
      { dataKey: 'orders', color: '#00d4ff', value: '订单数' },
      { dataKey: 'outbound', color: '#00ff88', value: '出库量' }
    ];
    
    return (
      <div className="flex space-x-4 px-4">
        {legendItems.map((entry) => {
          const isVisible = visibleLines[entry.dataKey as keyof typeof visibleLines];
          return (
            <div
              key={entry.dataKey}
              className={`flex items-center space-x-2 px-4 py-2 rounded-xl cursor-pointer 
                ${isVisible ? 'bg-white/10' : 'bg-white/5'} 
                backdrop-blur-sm border border-white/10 hover:bg-white/15 
                transition-all duration-300 transform hover:scale-105`}
              onClick={() => setVisibleLines(prev => ({
                ...prev,
                [entry.dataKey]: !prev[entry.dataKey as keyof typeof visibleLines]
              }))}
            >
              <div
                className={`w-3 h-3 rounded-full shadow-lg transition-opacity duration-300
                  ${isVisible ? 'opacity-100' : 'opacity-40'}`}
                style={{ backgroundColor: entry.color }}
              />
              <span className={`text-white font-medium text-sm transition-opacity duration-300
                ${isVisible ? 'opacity-100' : 'opacity-40'}`}>
                {entry.value}
              </span>
            </div>
          );
        })}
      </div>
    );
  };

  // 修改饼图图例组件
  const CustomPieLegend = () => {
    if (!orderTypeData.length) return null;
    
    return (
      <div className="space-y-3">
        {orderTypeData.map((entry, index) => {
          const isVisible = visiblePieSegments[entry.name] ?? true;
          return (
            <div 
              key={index} 
              className={`flex items-center justify-between p-3 rounded-xl 
                ${isVisible ? 'bg-white/10' : 'bg-white/5'} 
                backdrop-blur-sm border border-white/10 hover:bg-white/15 
                transition-all duration-300 group cursor-pointer`}
              onClick={() => setVisiblePieSegments(prev => ({
                ...prev,
                [entry.name]: !prev[entry.name]
              }))}
            >
              <div className="flex items-center space-x-3">
                <div 
                  className={`w-4 h-4 rounded-full shadow-lg transition-all duration-300
                    ${isVisible ? 'animate-pulse' : 'opacity-40'} 
                    group-hover:scale-125`}
                  style={{ backgroundColor: entry.color }}
                />
                <span className={`text-gray-300 font-medium transition-opacity duration-300
                  ${isVisible ? 'opacity-100' : 'opacity-40'}`}>
                  {entry.name}
                </span>
              </div>
              <div className="flex items-center space-x-2">
                <span className={`text-white font-bold text-lg transition-opacity duration-300
                  ${isVisible ? 'opacity-100' : 'opacity-40'}`}>
                  {entry.value}%
                </span>
                <Sparkles className={`w-4 h-4 text-yellow-400 transition-opacity duration-300
                  ${isVisible ? 'group-hover:opacity-100' : 'opacity-0'}`} />
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-900 via-blue-900 to-purple-900 p-4 relative overflow-hidden">
      {/* 背景动效 - 更华丽的设计 */}
      <div className="absolute inset-0 overflow-hidden">
        <div className="absolute top-0 left-0 w-full h-full">
          {/* 增强的粒子效果 */}
          {Array.from({ length: 80 }).map((_, i) => (
            <div
              key={i}
              className={`absolute rounded-full animate-pulse ${
                i % 4 === 0 ? 'w-2 h-2 bg-blue-400' :
                i % 4 === 1 ? 'w-1.5 h-1.5 bg-purple-400' :
                i % 4 === 2 ? 'w-1 h-1 bg-cyan-400' :
                'w-0.5 h-0.5 bg-pink-400'
              }`}
              style={{
                left: `${Math.random() * 100}%`,
                top: `${Math.random() * 100}%`,
                animationDelay: `${Math.random() * 5}s`,
                animationDuration: `${2 + Math.random() * 4}s`
              }}
            />
          ))}
          
          {/* 流星效果 */}
          {Array.from({ length: 5 }).map((_, i) => (
            <div
              key={`meteor-${i}`}
              className="absolute w-1 h-20 bg-gradient-to-b from-cyan-400 to-transparent rounded-full animate-pulse opacity-30"
              style={{
                left: `${Math.random() * 100}%`,
                top: `${Math.random() * 100}%`,
                transform: `rotate(${Math.random() * 360}deg)`,
                animationDelay: `${Math.random() * 3}s`,
                animationDuration: `${3 + Math.random() * 2}s`
              }}
            />
          ))}
          
          {/* 增强的光束流动效果 */}
          <div className="absolute top-1/4 left-0 w-full h-px bg-gradient-to-r from-transparent via-cyan-400 to-transparent animate-pulse opacity-40" />
          <div className="absolute top-1/2 left-0 w-full h-px bg-gradient-to-r from-transparent via-purple-400 to-transparent animate-pulse opacity-40" style={{ animationDelay: '1s' }} />
          <div className="absolute top-3/4 left-0 w-full h-px bg-gradient-to-r from-transparent via-pink-400 to-transparent animate-pulse opacity-40" style={{ animationDelay: '2s' }} />
          
          {/* 圆形光晕效果 */}
          <div className="absolute top-10 right-10 w-32 h-32 bg-gradient-to-r from-blue-400/20 to-purple-400/20 rounded-full blur-xl animate-pulse" />
          <div className="absolute bottom-10 left-10 w-40 h-40 bg-gradient-to-r from-cyan-400/20 to-pink-400/20 rounded-full blur-xl animate-pulse" style={{ animationDelay: '1s' }} />
        </div>
      </div>

      <div className="relative z-10 space-y-8">
        {/* 顶部标题栏 - 更华丽的设计 */}
        <div className="text-center mb-10 animate-fade-in">
          <div className="relative inline-block">
            <h1 className="text-5xl font-bold text-white mb-4 bg-gradient-to-r from-cyan-400 via-blue-400 to-purple-400 bg-clip-text text-transparent animate-pulse">
              物流数据可视化大屏
            </h1>
            <div className="absolute -top-2 -right-2">
              <Sparkles className="w-8 h-8 text-yellow-400 animate-spin" />
            </div>
            <div className="absolute -bottom-2 -left-2">
              <Star className="w-6 h-6 text-pink-400 animate-pulse" />
            </div>
          </div>
          <div className="flex items-center justify-center space-x-12 text-gray-300 mt-6">
            <div className="flex items-center space-x-3 bg-white/10 backdrop-blur-sm rounded-full px-6 py-3 border border-white/20 hover:bg-white/20 transition-all duration-300 transform hover:scale-105">
              <div className="w-4 h-4 bg-gradient-to-r from-green-400 to-emerald-400 rounded-full animate-pulse shadow-lg" />
              <span className="font-semibold">系统运行正常</span>
              <Zap className="w-4 h-4 text-yellow-400" />
            </div>
            <div className="flex items-center space-x-3 bg-white/10 backdrop-blur-sm rounded-full px-6 py-3 border border-white/20 hover:bg-white/20 transition-all duration-300 transform hover:scale-105">
              <Clock className="w-5 h-5 text-cyan-400" />
              <span className="font-mono text-lg">{currentTime.toLocaleString('zh-CN')}</span>
            </div>
            {/* 月份选择器 - 更华丽的设计 */}
            <div className="flex items-center space-x-3 bg-white/10 backdrop-blur-sm rounded-full px-6 py-3 border border-white/20 hover:bg-white/20 transition-all duration-300 transform hover:scale-105">
              <Calendar className="w-5 h-5 text-cyan-400" />
              <div className="relative">
                <select
                  value={selectedMonth}
                  onChange={(e) => setSelectedMonth(e.target.value)}
                  className="bg-transparent border-none text-white text-lg font-semibold focus:outline-none appearance-none cursor-pointer pr-8"
                >
                  {monthOptions.map((option) => (
                    <option key={option.value} value={option.value} className="bg-gray-800 text-white">
                      {option.label}
                    </option>
                  ))}
                </select>
                <div className="absolute right-0 top-1/2 transform -translate-y-1/2 pointer-events-none">
                  <ChevronDown className="w-5 h-5 text-cyan-400" />
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* 核心KPI指标 - 更华丽的设计 */}
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-6 mb-8">
          {[
            {
              title: '本月订单',
              value: dashboardStats.monthlyOrders.toLocaleString(),
              icon: Package,
              color: 'from-cyan-500 to-blue-600',
              bgColor: 'from-cyan-500/20 to-blue-600/20',
              shadowColor: 'shadow-cyan-500/25'
            },
            {
              title: '本月出库量',
              value: dashboardStats.monthlyOutbound.toLocaleString(),
              icon: BarChart3,
              color: 'from-orange-500 to-red-600',
              bgColor: 'from-orange-500/20 to-red-600/20',
              shadowColor: 'shadow-orange-500/25'
            },
            {
              title: '客户总数',
              value: dashboardStats.totalCustomers.toString(),
              icon: Users,
              color: 'from-indigo-500 to-purple-600',
              bgColor: 'from-indigo-500/20 to-purple-600/20',
              shadowColor: 'shadow-indigo-500/25'
            },
            {
              title: '货物品类',
              value: dashboardStats.productCategories.toString(),
              icon: Target,
              color: 'from-green-500 to-emerald-600',
              bgColor: 'from-green-500/20 to-emerald-600/20',
              shadowColor: 'shadow-green-500/25'
            }
          ].map((kpi, index) => (
            <div
              key={index}
              className={`relative overflow-hidden rounded-3xl bg-gradient-to-br ${kpi.bgColor} backdrop-blur-sm border border-white/10 p-6 group hover:scale-105 transition-all duration-500 ${kpi.shadowColor} shadow-xl hover:shadow-2xl animate-slide-up`}
              style={{ animationDelay: `${index * 0.1}s` }}
            >
              <div className="absolute inset-0 bg-gradient-to-br from-white/10 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500" />
              <div className="relative">
                <div className="flex items-center justify-between mb-4">
                  <div className={`p-3 rounded-2xl bg-gradient-to-r ${kpi.color} shadow-lg transform group-hover:scale-110 transition-transform duration-300`}>
                    <kpi.icon className="w-8 h-8 text-white" />
                  </div>
                </div>
                <div className="space-y-2">
                  <p className="text-3xl font-bold text-white group-hover:text-4xl transition-all duration-300">
                    {kpi.value}
                  </p>
                  <p className="text-sm text-gray-300 font-medium">{kpi.title}</p>
                </div>
              </div>
              <div className="absolute bottom-0 left-0 w-full h-2 bg-gradient-to-r from-transparent via-white/30 to-transparent animate-pulse" />
              <div className="absolute top-2 right-2 w-2 h-2 bg-white/50 rounded-full animate-ping" />
            </div>
          ))}
        </div>

        {/* 主要图表区域 - 更华丽的设计 */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* 日度订单趋势 - 修复版本 */}
          <div className="lg:col-span-2">
            <div className="bg-gray-900/60 backdrop-blur-lg border border-white/10 rounded-3xl p-8 h-96 shadow-2xl hover:shadow-3xl transition-all duration-500 group">
              <div className="flex items-center justify-between mb-6">
                <div className="flex items-center space-x-3">
                  <div className="p-2 bg-gradient-to-r from-blue-500 to-purple-500 rounded-xl">
                    <BarChart3 className="w-6 h-6 text-white" />
                  </div>
                  <h3 className="text-xl font-bold text-white">
                    {monthOptions.find(m => m.value === selectedMonth)?.label} 订单与出库量趋势
                  </h3>
                </div>
              </div>
              {dailyOrderData.length > 0 ? (
                <ResponsiveContainer width="100%" height="100%">
                  <AreaChart data={dailyOrderData} key={animationKey}>
                    <defs>
                      <linearGradient id="orderGradient" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="5%" stopColor="#00d4ff" stopOpacity={0.8}/>
                        <stop offset="95%" stopColor="#00d4ff" stopOpacity={0.1}/>
                      </linearGradient>
                      <linearGradient id="outboundGradient" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="5%" stopColor="#00ff88" stopOpacity={0.8}/>
                        <stop offset="95%" stopColor="#00ff88" stopOpacity={0.1}/>
                      </linearGradient>
                    </defs>
                    <CartesianGrid strokeDasharray="3 3" stroke="#374151" opacity={0.3} />
                    <XAxis dataKey="day" stroke="#9CA3AF" fontSize={12} />
                    <YAxis yAxisId="left" stroke="#9CA3AF" fontSize={12} />
                    <YAxis yAxisId="right" orientation="right" stroke="#9CA3AF" fontSize={12} />
                    <Tooltip 
                      content={<DarkTooltip 
                        formatter={(value: any, name: string) => [
                          value, 
                          name === 'orders' ? '订单数' : '出库量'
                        ]}
                      />}
                    />
                    <Legend 
                      content={<CustomAreaLegend />}
                      verticalAlign="top"
                      align="right"
                      wrapperStyle={{
                        paddingTop: "10px",
                        paddingRight: "20px",
                        paddingBottom: "20px"
                      }}
                    />
                    {visibleLines.orders && (
                      <Area
                        yAxisId="left"
                        type="monotone"
                        dataKey="orders"
                        stroke="#00d4ff"
                        strokeWidth={3}
                        fill="url(#orderGradient)"
                        dot={{ fill: '#00d4ff', strokeWidth: 2, r: 6 }}
                        activeDot={{ r: 8, stroke: '#00d4ff', strokeWidth: 2 }}
                        name="订单数"
                      />
                    )}
                    {visibleLines.outbound && (
                      <Area
                        yAxisId="right"
                        type="monotone"
                        dataKey="outbound"
                        stroke="#00ff88"
                        strokeWidth={3}
                        fill="url(#outboundGradient)"
                        dot={{ fill: '#00ff88', strokeWidth: 2, r: 6 }}
                        activeDot={{ r: 8, stroke: '#00ff88', strokeWidth: 2 }}
                        name="出库量"
                      />
                    )}
                  </AreaChart>
                </ResponsiveContainer>
              ) : (
                <div className="flex items-center justify-center h-full">
                  <div className="text-center">
                    <div className="relative">
                      <BarChart3 className="w-20 h-20 text-gray-500 mx-auto mb-4 animate-pulse" />
                      <div className="absolute top-0 left-1/2 transform -translate-x-1/2 w-4 h-4 bg-blue-400 rounded-full animate-ping"></div>
                    </div>
                    <p className="text-gray-400 text-xl font-semibold">暂无数据</p>
                    <p className="text-gray-500 text-sm">请选择其他月份或检查数据源</p>
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* 订单类型分布 */}
          <div className="bg-gray-900/60 backdrop-blur-lg border border-white/10 rounded-3xl p-8 h-96 shadow-2xl hover:shadow-3xl transition-all duration-500 group">
            <div className="flex items-center justify-between mb-6">
              <div className="flex items-center space-x-3">
                <PieChartIcon className="w-8 h-8 text-purple-500" />
                <h2 className="text-xl font-bold text-white">订单类型分布</h2>
              </div>
              <div className="text-sm text-gray-400">{selectedMonth}</div>
            </div>
            {orderTypeData.length > 0 ? (
              <div className="h-[calc(100%-3rem)] flex items-center">
                <div className="w-full h-full flex">
                  <div className="w-2/3 h-full">
                    <ResponsiveContainer width="100%" height="100%">
                      <PieChart>
                        <defs>
                          <filter id="glow">
                            <feGaussianBlur stdDeviation="3" result="coloredBlur"/>
                            <feMerge>
                              <feMergeNode in="coloredBlur"/>
                              <feMergeNode in="SourceGraphic"/>
                            </feMerge>
                          </filter>
                        </defs>
                        <Pie
                          data={orderTypeData.filter(item => visiblePieSegments[item.name])}
                          cx="50%"
                          cy="50%"
                          innerRadius={60}
                          outerRadius={90}
                          paddingAngle={8}
                          dataKey="value"
                          nameKey="name"
                          animationBegin={0}
                          animationDuration={1500}
                          filter="url(#glow)"
                        >
                          {orderTypeData.filter(item => visiblePieSegments[item.name]).map((entry, index) => (
                            <Cell 
                              key={`cell-${index}`} 
                              fill={entry.color}
                              stroke={entry.color}
                              strokeWidth={2}
                            />
                          ))}
                        </Pie>
                        <Tooltip content={<CustomPieTooltip />} />
                      </PieChart>
                    </ResponsiveContainer>
                  </div>
                  <div className="w-1/3 h-full flex items-center justify-center">
                    <CustomPieLegend />
                  </div>
                </div>
              </div>
            ) : (
              <div className="h-full flex items-center justify-center">
                <div className="text-gray-500 animate-pulse">加载中...</div>
              </div>
            )}
          </div>
        </div>

        {/* 热门货物出库量排行 - 增强版 */}
        <div className="bg-gray-900/60 backdrop-blur-lg border border-white/10 rounded-3xl p-8 shadow-2xl hover:shadow-3xl transition-all duration-500">
          <div className="flex items-center justify-between mb-8">
            <div className="flex items-center space-x-3">
              <div className="p-3 bg-gradient-to-r from-green-500 to-emerald-500 rounded-xl">
                <Package className="w-8 h-8 text-white" />
              </div>
              <h3 className="text-2xl font-bold text-white">热门货物出库量排行</h3>
            </div>
            <div className="flex items-center space-x-2">
              <Star className="w-6 h-6 text-yellow-400 animate-pulse" />
              <span className="text-yellow-400 font-semibold">TOP排行榜</span>
            </div>
          </div>
          {popularProductData.length > 0 ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {popularProductData.map((item, index) => (
                <div 
                  key={index} 
                  className="bg-gradient-to-br from-white/10 to-white/5 rounded-2xl p-6 border border-white/10 hover:bg-white/20 transition-all duration-500 group transform hover:scale-105 hover:shadow-2xl animate-slide-up"
                  style={{ animationDelay: `${index * 0.1}s` }}
                >
                  <div className="flex items-center justify-between mb-4">
                    <div className="flex items-center space-x-3">
                      <div className={`w-10 h-10 rounded-2xl flex items-center justify-center shadow-lg transform group-hover:scale-110 transition-transform duration-300 ${
                        index === 0 ? 'bg-gradient-to-r from-yellow-400 to-orange-500' :
                        index === 1 ? 'bg-gradient-to-r from-gray-400 to-gray-600' :
                        index === 2 ? 'bg-gradient-to-r from-orange-400 to-red-500' :
                        'bg-gradient-to-r from-blue-400 to-purple-500'
                      }`}>
                        {index < 3 ? (
                          <Award className="w-6 h-6 text-white" />
                        ) : (
                          <span className="text-white font-bold text-lg">{index + 1}</span>
                        )}
                      </div>
                      <div>
                        <span className="text-white font-bold text-lg group-hover:text-cyan-400 transition-colors duration-300">
                          {item.name}
                        </span>
                        <div className="flex items-center space-x-2 mt-1">
                          <Badge variant="info" size="sm" className="bg-blue-500/20 text-blue-300 border-blue-400/30">
                            {item.unit}
                          </Badge>
                          {index < 3 && (
                            <div className="flex items-center space-x-1">
                              <Star className="w-3 h-3 text-yellow-400" />
                              <span className="text-yellow-400 text-xs font-semibold">TOP {index + 1}</span>
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  </div>
                  <div className="space-y-3">
                    <div className="flex items-center justify-between p-3 rounded-xl bg-white/5 backdrop-blur-sm border border-white/10">
                      <div className="flex items-center space-x-2">
                        <Box className="w-4 h-4 text-cyan-400" />
                        <span className="text-gray-400 text-sm">总出库量</span>
                      </div>
                      <div className="flex items-center space-x-2">
                        <span className="text-2xl font-bold text-cyan-400 group-hover:text-3xl transition-all duration-300">
                          {item.outbound.toLocaleString()}
                        </span>
                        <TrendingUp className="w-4 h-4 text-green-400" />
                      </div>
                    </div>
                    <div className="flex items-center justify-between p-3 rounded-xl bg-white/5 backdrop-blur-sm border border-white/10">
                      <div className="flex items-center space-x-2">
                        <ShoppingCart className="w-4 h-4 text-green-400" />
                        <span className="text-gray-400 text-sm">相关订单</span>
                      </div>
                      <div className="flex items-center space-x-2">
                        <span className="text-lg font-bold text-green-400">{item.orders}</span>
                        <span className="text-green-400 text-sm">单</span>
                      </div>
                    </div>
                  </div>
                  <div className="mt-4 h-1 bg-gradient-to-r from-cyan-400 via-blue-400 to-purple-400 rounded-full opacity-0 group-hover:opacity-100 transition-opacity duration-500 animate-pulse" />
                </div>
              ))}
            </div>
          ) : (
            <div className="flex items-center justify-center py-20">
              <div className="text-center">
                <div className="relative">
                  <Package className="w-24 h-24 text-gray-500 mx-auto mb-6 animate-pulse" />
                  <div className="absolute top-0 right-0 w-6 h-6 bg-yellow-400 rounded-full animate-bounce"></div>
                </div>
                <p className="text-gray-400 text-2xl font-semibold">暂无数据</p>
                <p className="text-gray-500 text-lg">请选择其他月份或检查数据源</p>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};